package br.com.sgi.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import br.com.sgi.autentication.UsuarioLogado;
import br.com.sgi.dao.AuthorityDao;
import br.com.sgi.model.Authority;
import br.com.sgi.service.AuthorityService;
@Service("authorityService")
public class AuthorityServiceImpl implements AuthorityService {

	@Autowired
	private AuthorityDao authorityDao;
	
	@Override
	public List<Authority> buscarTodasAuthority() {
		
		 Map<String, Object>  params = new HashMap<String, Object>();
		 params.put("ativo", true);
			StringBuffer sql = new StringBuffer();
			
			sql.append("\n SELECT a FROM Authority a");
			sql.append( "\n WHERE a.ativo  = :ativo ");
			sql.append( "\n AND a.sistema.coSeqSistema = :coSistema");
		
		return authorityDao.findByNativeQuery(sql.toString(), params);
	}
	
	@Override
	public Authority buscarAuthorityPorNome(String nome) {
		
		 Map<String, Object>  params = new HashMap<String, Object>();
		 params.put("ativo", true);
		 params.put("authority", nome);
			StringBuffer sql = new StringBuffer();
			
			sql.append("\n SELECT a FROM Authority a");
			sql.append( "\n WHERE a.ativo  = :ativo ");
			sql.append( "\n AND a.sistema.coSeqSistema = :coSistema");
			sql.append( "\n AND a.authority = :authority");
		
			List<Authority> list = authorityDao.findByNativeQuery(sql.toString(), params);
			if(list == null || list.isEmpty())
				return null;
			
				
			
		return list.get(0); 
	}

	@Override
	@Transactional
	public String buscarDescricaoPorAuthoriby(String authority) {
		Criteria crit = authorityDao.getCriteria();		
		String authoDescricao = "";
		
			crit.add(Restrictions.like("authority", "%"+authority+"%"));
			List<Authority> list = crit.list();
			if(list != null && list.size() > 0)
				authoDescricao = list.get(0).getDescricao() ;
		
		return authoDescricao;
	}

}
